package com.itheima.eurekaprovider.dao.impl;

import com.itheima.eurekaprovider.dao.UserDao;
import com.itheima.eurekaprovider.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public User findByUser(String username, String password) {
        String sql = "select * from user where username=? and password =?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql, rowMapper, username, password);
        } catch (Exception e) {
            user = null;
        }
        return user;
    }

    @Override
    public User findByUser(User user) {
        String sql = "select * from user where username=? and password =?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User newuser = null;
        try {
            newuser = this.jdbcTemplate.queryForObject(sql, rowMapper, user.getUsername(), user.getPassword());
        } catch (Exception e) {
            newuser = null;
        }
        return newuser;
    }

    @Override
    public List<User> findAll() {
        String sql = "select * from user";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        List<User> list = this.jdbcTemplate.query(sql, rowMapper);
        return list;
    }

    @Override
    public Integer add(User user) {
        String sql = "insert into user (username,password) values(?,?)";
        int num = this.jdbcTemplate.update(sql, user.getUsername(),user.getPassword());
        return num;
    }

    @Override
    public Integer update(User user) {
        String sql = "update user set username=?,password=? where id=?";
        Object[] params = new Object[]{
                user.getUsername(), user.getPassword(), user.getId()
        };
        int num = this.jdbcTemplate.update(sql,params);
        return num;
    }

    @Override
    public Integer delete(Integer id) {
        String sql = "delete from user where id=?";
        int num = this.jdbcTemplate.update(sql,id);
        return num;
    }
}
